package org.huangrui.juc.source.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 *  CAS----Unsafe----do while+ABA---AtomicStampedReference,AtomicMarkableReference
 *  AtomicStampedReference,version号，+1；
 *  AtomicMarkableReference，判断一次性，false，true
 * @Author hr
 * @Create 2024-04-05 04:23
 */
public class T03_AtomicMarkableReference {
    static AtomicMarkableReference<Integer> markableReference = new AtomicMarkableReference<>(100,false);
    public static void main(String[] args) {
        new Thread(() ->{
            boolean marked = markableReference.isMarked();
            //暂停秒钟
            try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            boolean b;
            b = markableReference.compareAndSet(100,200,marked,!marked);
            System.out.println("t1..1.." +b);
            System.out.println(Thread.currentThread().getName()+"\t -----come in "+ markableReference.getReference()+"--"+markableReference.isMarked());
            b = markableReference.compareAndSet(200,100,markableReference.isMarked(),!markableReference.isMarked());
            System.out.println("t1..2.." +b);
            System.out.println(Thread.currentThread().getName()+"\t -----come in "+ markableReference.getReference()+"--"+markableReference.isMarked());
        },"t1").start();

        new Thread(() ->{
            boolean marked = markableReference.isMarked();
            //暂停秒钟
            try { TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
            boolean b = markableReference.compareAndSet(100,300,marked,!marked);
            System.out.println("t2..1.." +b);
             System.out.println(Thread.currentThread().getName()+"\t -----come in "+ markableReference.getReference()+"--"+markableReference.isMarked());

        },"t2").start();
    }
}
